from typing import Any
import httpx
import json
from mcp.server.fastmcp import FastMCP

# Initialize FastMCP server
mcp = FastMCP("community-key-kpi-server", host="0.0.0.0", port=8080)

API_URL = "http://121.36.32.255/api/codecheckAccess/ci-portal/v2/dashboard/top10/component"

@mcp.tool()
def get_community_code_statistics(startTime: str, endTime: str):
    """获取社区代码量统计数据
    
    Args:
        startTime: 开始时间 Timestamp
        endTime: 结束时间 Timestamp

    Returns:
        json: 从开始时间到结束时间的社区代码量统计数据
    """
    try:
        # 将startTime参数末尾添加三个0
        startTime = startTime + "000"
        # 将endTime参数末尾添加三个0
        endTime = endTime + "000"

        headers = {
            "Content-Type": "application/json",
        }

        request = {
            "startTime": startTime,
            "endTime": endTime
        }
        url = "http://121.36.32.255/api/statistics/webhook/statistics/v1/code/amount"   

        response = httpx.post(url, timeout=10, headers=headers, json=request)
        response.raise_for_status()
        data = response.json()

    except Exception as e:
        return {"code": "50000", "message": "请求失败", "data": []}
    
    # 字段映射
    field_mapping = {
        "dateStr": "日期",
        "additions": "新增代码行数",
        "deletions": "删除代码行数",
        "changeNum": "变更总行数"
    }
    
    # 转换数据字段为中文
    if data.get("code") == "20000" and "data" in data and isinstance(data["data"], list):
        translated_data = []
        for item in data["data"]:
            translated_item = {}
            for key, value in item.items():
                if key in field_mapping:
                    translated_item[field_mapping[key]] = value
                else:
                    translated_item[key] = value
            translated_data.append(translated_item)
        
        data["data"] = translated_data
        data["message"] = "请求成功"

    return data




@mcp.tool()
def get_build_data_for_analysis(user_question: str = "") -> str:
    """获取OpenHarmony构建数据供分析
    
    Args:
        user_question: 用户的问题（可选，用于上下文）
    
    Returns:
        完整的构建数据JSON，供大模型分析回答用户问题
    """
    try:
        response = httpx.get(API_URL, timeout=10)
        response.raise_for_status()
        data = response.json()
    except:
        # 使用示例数据
        data = {"code": "20000", "message": "请求成功", "data": []}  # 你的示例数据
    
    # 添加上下文信息
    context = {
        "user_question": user_question,
        "data_description": "OpenHarmony Top 10组件构建质量数据",
        "key_metrics": {
            "buildSuccessRate": "构建成功率(0-1)",
            "avrBuildDuration": "平均构建时长(秒)", 
            "totalBuildCount": "总构建次数",
            "manifestBranch": "分支名称",
            "component": "组件名称"
        },
        "api_data": data
    }
    
    return json.dumps(context, ensure_ascii=False, indent=2)


if __name__ == "__main__":
    mcp.run(transport='sse')